package com.zghhost.codedemo.mq.rabbitmq;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class ConnectionFactoryTest {
    public static String TEST_EX_NAME = "exname";
    public static String TEST_Q_NAME = "qname";

    public static String ROUTING_KEY = "direct";

    private static Connection conn;

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
//        factory.setUri("amqp://guest:guest@127.0.0.1:5672/");
//        factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost");
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        factory.setHost("127.0.0.1");
        factory.setPort(5672);

        //打开连接和通道
        conn = factory.newConnection();
        Channel channel = conn.createChannel();

        //声明交换器和队列 并进行绑定
        channel.exchangeDeclare(TEST_EX_NAME, ROUTING_KEY, true);
        channel.queueDeclare(TEST_Q_NAME, true, false, false, null);
        AMQP.Queue.BindOk bindOk = channel.queueBind(TEST_Q_NAME, TEST_EX_NAME, ROUTING_KEY);

        //获取队列操作句柄
        AMQP.Queue.DeclareOk response = channel.queueDeclarePassive(TEST_Q_NAME);
        // returns the number of messages in Ready state in the queue
        System.out.println(response.getMessageCount());
        // returns the number of consumers the queue has
        System.out.println(response.getConsumerCount());

        //发送一条消息
        byte[] messageBodyBytes = "Hello, world!".getBytes();
        channel.basicPublish(TEST_EX_NAME, ROUTING_KEY, null, messageBodyBytes);
    }

    public static void openConnection() throws Exception {
        if(conn == null || !conn.isOpen()){
            conn = new ConnectionFactory().newConnection();
        }
    }

    public static void closeConnection()throws Exception{
        if(conn != null && conn.isOpen()){
            conn.close();
        }
    }

    public static Channel getNewChannel() throws Exception{
        openConnection();
        return conn.createChannel();
    }
}
